<script lang="ts" setup>
import { keys } from 'lodash'
import { useVModel } from '@vueuse/core'
import { useSystemStore } from '~/stores/system'
import { isMediaUrl } from '~/database/utils'

const ORDERS: Record<string, string> = {
  ascending: 'asc',
  descending: 'desc'
}

interface IColumn {
  prop: string
  label: string
  [key: string]: any
}

interface IProps {
  total: number
  data: Record<string, any>[]
  columns: IColumn[]
  no: number
  size: number
  restRef: ant
}

const tableWidth = ref('100%')
const tableHeight = ref('100%')

const slots = useSlots()
const emit = defineEmits([
  'pageChange', 
  'update:no', 
  'update:size',
  'sortChange'
])
const props = defineProps<IProps>()

const sysStore = useSystemStore()

const no = useVModel(props, 'no', emit)
const size = useVModel(props, 'size', emit)

const pageRef =  ref<HTMLElement | null>(null)

const hasSlot = (prop: string) => {
  return keys(slots).includes(prop)
}

const pageChange = () => {
  emit('pageChange', { no: no.value, size: size.value })
}

const adjustTableWidth = () => {
  const viewportWidth = window.innerWidth
  const W = viewportWidth - 200 - 16 * 2
  tableWidth.value = `${W}px`
}

const adjustTableHeight = () => {
  const viewportHeight= window.innerHeight
  const searchHeight = props.restRef.clientHeight
  const pageHeight = pageRef.value.clientHeight
  const H = viewportHeight - 48 - searchHeight - pageHeight
  tableHeight.value = `${H - 60}px`
}

const adjustTableSize = () => {
  adjustTableWidth()
  adjustTableHeight()
}

watch(() => sysStore.collapsed, () => {
  nextTick(adjustTableSize)
})

onMounted(() => {
  nextTick(adjustTableSize)
  window.addEventListener('resize', adjustTableSize)
})

onUnmounted(() => {
  window.removeEventListener('resize', adjustTableSize)
})

const onSortChange = (args: any) => {
  emit('sortChange', [
    {
      field: args.prop,
      direction: ORDERS[args.order]
    }
  ])
}
</script>

<template>
  <div class="table-container">
    <el-table 
      :data="data" 
      border 
      :style="{ width: tableWidth, height: tableHeight }"
      :sort-orders="['asc', 'desc']"
      @sort-change="onSortChange">
      <template v-for="col in columns" :key="col.prop">
        <el-table-column sortable align="center" v-bind="col" :prop="col.prop">
          <template v-if="hasSlot(col.prop)" v-slot="scope">
            <slot :name="col.prop" :row="scope.row" :column="col" />
          </template>
          <template v-else v-slot="scope">
            <div class="flex justify-center items-center" v-if="isMediaUrl(scope.row[col.prop]) === 'image'">
              <img :src="scope.row[col.prop]" />
            </div>
            <div class="h-full w-full" v-else-if="isMediaUrl(scope.row[col.prop]) === 'video'">
              <video controls style="width: 100%;">
                <source :src="scope.row[col.prop]" type="video/mp4">
              </video>
            </div>
            <div class="h-full w-full" v-else-if="isMediaUrl(scope.row[col.prop]) === 'audio'">
              <audio controls style="width: 100%;">
                <source :src="scope.row[col.prop]" type="audio/mpeg">
              </audio>
            </div>
            <div v-else-if="isMediaUrl(scope.row[col.prop]) === 'link'">
              <a :href="scope.row[col.prop]" target="_blank">{{ scope.row[col.prop] }}</a>
            </div>
            <div v-else>
              {{ scope.row[col.prop] }}
            </div>
          </template>
        </el-table-column>
      </template>
      <el-table-column width="220" fixed="right" align="center" :label="$t('action')">
        <template #default="scope">
          <slot name="operation" v-bind="scope" />
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div ref="pageRef" class="pager flex justify-end">
    <el-pagination layout="total, prev, pager, next" :total="total" v-model:page-size="size" v-model:current-page="no"
      @size-change="pageChange" @current-change="pageChange" />
  </div>
</template>

<style lang="scss" scoped>
.pager {
  margin-top: 16px;
}
</style>
